package classLoader;

import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义类加载器
 */
public class MyClassLoader extends ClassLoader {

    public MyClassLoader() {
        super(null);
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        String className = null;
        if (name != null && !"".equals(name)) {
            if (name.startsWith("java.lang")) {
                className = new StringBuilder("/").append(name.replace('.', '/')).append(".class").toString();
            } else {
                className = new StringBuilder(name.substring(name.lastIndexOf('.') + 1)).append(".class").toString();
            }
            System.out.println(className);
            InputStream is = getClass().getResourceAsStream(className);
            System.out.println(is);
            if (is == null) return super.loadClass(name);
            byte[] bytes = null;
            try {
                bytes = new byte[is.available()];
                is.read(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return defineClass(name, bytes, 0, bytes.length);
        }

        return super.loadClass(name);
    }
}
